package il.ac.biu.cs.grossmm.xmlUtil;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Xml {
	public static String getReference(Element element, String childName)
			throws XmlException {
		String val = getRequiredElement(element, childName).getAttribute("ref");
		assert (val.length() > 0);
		return val;
	}

	public static String getRequiredAttribute(Element element, String attrName)
			throws XmlException {
		String v = element.getAttribute(attrName);

		if (v.equals(""))
			throw new XmlException(element, "Attribute '" + attrName
					+ "' not found");

		return v;
	}

	public static String getRequiredAttribute(Element element, String elmName,
			String attrName) throws XmlException {
		return getRequiredAttribute(getRequiredElement(element, elmName),
				attrName);
	}

	public static Element getSingleElement(Element element, String name) {

		NodeList nodeList = element.getChildNodes();

		for (int i = 0; i < nodeList.getLength(); i++) {
			Node n = nodeList.item(i);
			if (n.getNodeType() == Node.ELEMENT_NODE
					&& n.getNodeName().equals(name))
				return (Element) n;
		}
		return null;
	}

	public static Element getRequiredElement(Element element, String name)
			throws XmlException {
		Element e = getSingleElement(element, name);
		if (e == null)
			throw new XmlException(element, "Element " + name + " not found");
		else
			return e;
	}

	public static void parseChldren(Element element, String name,
			ElementParser parser) throws XmlException {
		for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
			if (node.getNodeType() != Node.ELEMENT_NODE)
				continue;

			Element e = (Element) node;

			if (e.getNodeName().equals(name))
				parser.parse(e);
		}
	}
}
